using System.IO;
using log4net.Core;

namespace Quiki.DocumentPostprocessors
{
    public class ParsingInfoGenerator : IDocumentPostprocessor
    {
        public ParsingInfoGenerator(
            DocumentProcessorSettings settings,
            ILogger logger)
        {
            this.settings = settings;
            this.logger = logger;
        }

        public void PostProcessDocument(WikiDocument document)
        {
            if (settings.GenerateParsingInfoFiles)
            {
                string outputFileName = document.ConstructFileName(settings.OutputDir, ".parse.txt");
                CreateDirectoryIfNecessary(outputFileName);

                using (StreamWriter writer = new StreamWriter(outputFileName))
                    document.RootElement.Dump(writer, 0);
            }
        }

        private void CreateDirectoryIfNecessary(string outputFileName)
        {
            string outputDirName = Path.GetDirectoryName(outputFileName);
            if (false == Directory.Exists(outputDirName))
            {
                logger.Log(Level.Debug, "Creating directory '{0}'", outputDirName);
                Directory.CreateDirectory(outputDirName);
            }
        }

        private readonly DocumentProcessorSettings settings;
        private readonly ILogger logger;
    }
}